// index.js

const api = require("../../../utils/request");
const util = require('../../../utils/util')
// 获取应用实例
const app = getApp()

Page({
  data: {
    appointment_time: util.formatDate(new Date()),
    appointment_range_type: 1,
    name: '',
    code: '',
    appointment_range: [
      { title: '中午', code: 0 },
      { title: '晚上', code: 1 }
    ],
    formData: {},
    rules: [{
      name: 'name',
      rules: { required: true, message: '真实姓名必填' },
    }]
  },
  onLoad(option) {
    const { code } = option;
    this.setData({
      code
    });
  },
  bindDateChange(e) {
    const { field } = e.currentTarget.dataset
    this.setData({
      [`formData.${field}`]: e.detail.value,
      appointment_time: e.detail.value
    })
  },
  bindRangeChange(e) {
    const { field } = e.currentTarget.dataset
    this.setData({
      [`formData.${field}`]: e.detail.value,
      appointment_range_type: e.detail.value
    })
  },
  formInputChange(e) {
    const { field } = e.currentTarget.dataset
    this.setData({
      [`formData.${field}`]: e.detail.value,
      name: e.detail.value
    })
  },
  submitForm() {
    this.selectComponent('#form').validate((valid, errors) => {
      console.log('valid', valid, errors)
      if (!valid) {
        const firstError = Object.keys(errors)
        if (firstError.length) {
          this.setData({
            error: errors[firstError[0]].message
          })
        }
      } else {
        const { appointment_time, appointment_range_type, name, code } = this.data;
        const body = {
          appointment_time,
          appointment_range_type,
          name: name.trim(),
          code
        };
        api.post('/bracelet-borrow/appointment', body)
          .then((res) => {
            if(res.code === '0' && res.msg === 'success') {
              wx.showToast({
                title: '预约成功'
              });
              // wx.reLaunch({
              //   url: '/pages/index/index',
              // })
            }
          })
      }
    })
  }
})
